package com.yydm.serviceacls.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yydm.serviceacls.dto.RoleDto;
import com.yydm.serviceacls.entity.Role;
import com.yydm.serviceacls.entity.RolePermission;
import com.yydm.serviceacls.service.RolePermissionService;
import com.yydm.serviceacls.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.yydm.commonutils.R;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色管理
 */
@RestController
@RequestMapping("/acl/role")
public class RoleController {

    @Autowired
    private RoleService roleServer;

    @Autowired
    private RolePermissionService roleAndPermissionServer;


    /**
     * 角色管理+模糊查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R page(int page, int pageSize, String name) {
        System.out.println(page + "" + pageSize);
        Page<Role> objectPage = new Page<>(page, pageSize);
        Page<RoleDto> roelPage = new Page<>();
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(name), Role::getName, name);
        roleServer.page(objectPage, queryWrapper);
        BeanUtils.copyProperties(objectPage, roelPage, "records");
        List<RoleDto> collect1 = objectPage.getRecords().stream().map(item -> {
            RoleDto roleDto = new RoleDto();
            BeanUtils.copyProperties(item, roleDto);
            Long id = item.getId();
            LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RolePermission::getRole_id, id);
            List<RolePermission> roleAndPermissions = roleAndPermissionServer.list(wrapper);
            if (roleAndPermissions != null) {
                List<Long> collect = roleAndPermissions.stream().map(ite -> {
                    Long permission_id = ite.getPermission_id();
                    return permission_id;
                }).collect(Collectors.toList());
                roleDto.setPermission_id(collect);
            }
            return roleDto;
        }).collect(Collectors.toList());
        roelPage.setRecords(collect1);
        return R.ok().data("page",roelPage);
    }

    /**
     * 新增角色
     *
     * @param role
     * @return
     */
    @PostMapping("saveRole")
    public R save(@RequestBody Role role) {
        boolean save = roleServer.save(role);
        if (save) {
            return R.ok().message("新增成功");
        }
        return R.error().message("新增失败");
    }

    /**
     * 更新角色
     *
     * @param role
     * @return
     */
    @PutMapping("updateRole")
    public R update(@RequestBody Role role) {
        System.out.println(role);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getId, role.getId());
        boolean update = roleServer.update(role, queryWrapper);
        if (update) {
            return R.ok().message("修改成功");
        }
        return R.error().message("修改失败");
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @DeleteMapping("delRole")
    public R delete(Long id) {
       roleServer.delete(id);
        return R.ok().message("删除成功");
    }

    /**
     * 获取所有的角色
     *
     * @return
     */
    @GetMapping("roleList")
    @PreAuthorize("hasAuthority('/user')")
    public R listName() {
        List<Role> list = roleServer.list();
        return R.ok().data("list",list);
    }

    /**
     * 角色更新和删除权限
     *
     * @param roleDto
     * @return
     */
    @PutMapping("/roleAndPer")
    public R userAndRole(@RequestBody RoleDto roleDto) {
        System.out.println(roleDto);
        //查询数据库中当前角色的所有权限
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getRole_id, roleDto.getId());
        List<RolePermission> list1 = roleAndPermissionServer.list(wrapper);
        //判断当前用户有没有权限，没有权限直接增加，有权限查看前台是否修改了
        if (list1 == null || list1.size() == 0) {
            for (Long rol : roleDto.getPermission_id()) {
                RolePermission ur = new RolePermission();
                ur.setRole_id(roleDto.getId());
                ur.setPermission_id(rol);
                boolean save = roleAndPermissionServer.save(ur);
            }
        } else {
            //遍历数据库里面当前角色所有的权限
            List<Long> role = roleDto.getPermission_id();
            for (Long rol : role) {
                //查询当前角色是否有当前权限
                LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(RolePermission::getRole_id, roleDto.getId());
                queryWrapper.eq(RolePermission::getPermission_id, rol);
                List<RolePermission> list = roleAndPermissionServer.list(queryWrapper);
                //如果没有增加权限
                if (list == null || list.size() == 0) {
                    RolePermission ur = new RolePermission();
                    ur.setRole_id(roleDto.getId());
                    ur.setPermission_id(rol);
                    boolean save = roleAndPermissionServer.save(ur);
                }
            }
            LinkedList<Long> list = new LinkedList<>();
            LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RolePermission::getRole_id, roleDto.getId());
            List<RolePermission> list3 = roleAndPermissionServer.list(queryWrapper);
            List<Long> permission_id1 = roleDto.getPermission_id();
            for (RolePermission p2 : list3) {
                Long permission_id = p2.getPermission_id();
                if (!list.contains(permission_id)) {
                    list.add(permission_id);
                }
            }
            for (Long p : permission_id1) {
                if (list.contains(p)) {
                    list.remove(p);
                }
            }
            for (Long l:list){
                LambdaQueryWrapper<RolePermission> wrapper1=new LambdaQueryWrapper<>();
                wrapper1.eq(RolePermission::getRole_id,roleDto.getId());
                wrapper1.eq(RolePermission::getPermission_id,l);
                roleAndPermissionServer.remove(wrapper1);
            }
        }

        return R.ok().message("操作成功");
    }


}
